package cn.lili.modules.union.serviceimpl;

import cn.lili.common.enums.ResultCode;
import cn.lili.common.event.TransactionCommitSendMQEvent;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.SnowFlake;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.exchange.AmqpExchangeProperties;
import cn.lili.modules.distribution.client.DistributionClient;
import cn.lili.modules.distribution.entity.dos.Distribution;
import cn.lili.modules.distribution.fallback.DistributionFallback;
import cn.lili.modules.member.entity.dos.*;
import cn.lili.modules.member.entity.dto.UnionAddDTO;
import cn.lili.modules.member.entity.dto.UnionMemberApplyDTO;
import cn.lili.modules.member.entity.enums.UnionMemberOptypeEnum;
import cn.lili.modules.member.entity.enums.UnionMemberStatusEnum;
import cn.lili.modules.member.service.UserService;
import cn.lili.modules.union.mapper.UnionMapper;
import cn.lili.modules.union.mapper.UnionMemberApplyMapper;
import cn.lili.modules.union.mapper.UnionMemberMapper;
import cn.lili.modules.union.service.UnionLogService;
import cn.lili.modules.union.service.UnionMemberApplyService;
import cn.lili.modules.union.service.UnionMemberService;
import cn.lili.mybatis.util.PageUtil;
import cn.lili.routing.UnionRoutingKey;
import cn.wildfirechat.pojos.PojoGroupMember;
import cn.wildfirechat.proto.ProtoConstants;
import cn.wildfirechat.sdk.GroupAdmin;
import com.api.UserApi;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pojos.OpenAppUser;
import io.netty.util.internal.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class UnionMemberApplyServiceImpl extends
        ServiceImpl<UnionMemberApplyMapper, UnionMemberApply>
        implements UnionMemberApplyService {

    private final UserService userService;

    private final UnionLogService unionLogService;

    @Resource
    private UserApi userApi;

    @Resource
    private UnionMemberApplyMapper unionMemberApplyMapper;

    @Resource
    private UnionMemberService unionMemberService;

    @Resource
    private UnionMapper unionMapper;

    @Resource
    private UnionMemberMapper unionMemberMapper;

    private final ApplicationEventPublisher applicationEventPublisher;

    private final AmqpExchangeProperties amqpExchangeProperties;

    @Resource
    private final DistributionClient distributionClient;

    @Override
    public void apply(UnionMemberApplyDTO unionMemberApplyDTO) {
        if(unionMemberApplyDTO.getMemberId().isEmpty()){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }
        if(unionMemberApplyDTO.getUnionId().isEmpty()){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }
        User user = userService.getById(unionMemberApplyDTO.getMemberId());
        if(null == user){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        Union union = unionMapper.selectById(unionMemberApplyDTO.getUnionId());
        if(null == union){
            throw  new ServiceException(ResultCode.PARAMS_ERROR);
        }

//        if(unionMemberApplyDTO.getMemberHead().isEmpty()){
//            throw new ServiceException(ResultCode.PARAMS_ERROR);
//        }
//        if(unionMemberApplyDTO.getMemberName().isEmpty()){
//            throw new ServiceException(ResultCode.PARAMS_ERROR);
//        }
        if(unionMemberApplyDTO.getCity().isEmpty()){
            unionMemberApplyDTO.setCity("海口");
        }

        UnionMember unionMember = unionMemberService.getByUnionMemberId(unionMemberApplyDTO.getMemberId());
        if(null != unionMember){
            throw new ServiceException(ResultCode.IN_OTHER_UNION);
        }


        LambdaQueryWrapper<UnionMemberApply> query = new LambdaQueryWrapper<>();
        query.eq(UnionMemberApply::getMemberId, unionMemberApplyDTO.getMemberId());
        query.eq(UnionMemberApply::getUnionId, unionMemberApplyDTO.getUnionId());
        //query.eq(UnionMemberApply::getOptype,UnionMemberOptypeEnum.APPLY.name());
        query.eq(UnionMemberApply::getStatus,UnionMemberStatusEnum.WAIT_APPLY.name());
        query.last("limit 1");
        UnionMemberApply exist = this.getOne(query);
        if(null!=exist){
            if (exist.getOptype().equals(UnionMemberOptypeEnum.INVITE.name())) {
                throw new ServiceException("该工会已邀请您加入工会，请在会长邀请中处理");
            }else {
                throw new ServiceException(ResultCode.APPLY_SAME_UNION);
            }
        }

        UnionMemberApply member = new UnionMemberApply(unionMemberApplyDTO);
        member.setStatus(UnionMemberStatusEnum.WAIT_APPLY.name());
        member.setOptype(UnionMemberOptypeEnum.APPLY.name());

        UnionLog unionLog = UnionLog.builder()
                .operationRemark("店主" + user.getUsername() + "申请加入工会:" + union.getUnionName())
                .createTime(new Date())
                .unionId(union.getId())
                .operationUserId(UserContext.getCurrentId())
                .operationUserName(Objects.requireNonNull(UserContext.getCurrentUser()).getUsername())
                .build();
        unionLogService.save(unionLog);

        this.save(member);
    }

    @Override
    public void invite(UnionMemberApplyDTO unionMemberApplyDTO) {
        if(unionMemberApplyDTO.getMemberId().isEmpty()){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        User user = userService.getById(unionMemberApplyDTO.getMemberId());
        if(null == user){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        Union union = unionMapper.selectById(unionMemberApplyDTO.getUnionId());
        if(null == union){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        if(!union.getChairmanId().equals(UserContext.getCurrentId())){
            //非会长邀请
            throw new ServiceException(ResultCode.INVALID_OPERATION);
        }

        if(unionMemberApplyDTO.getCity().isEmpty()){
            unionMemberApplyDTO.setCity("海口");
        }

        User chariman = userService.getById(union.getChairmanId());


        UnionMember unionMember = unionMemberService.getByUnionMemberId(unionMemberApplyDTO.getMemberId());
        if(null != unionMember){
            throw new ServiceException(ResultCode.IN_OTHER_UNION);
        }

        LambdaQueryWrapper<UnionMemberApply> query = new LambdaQueryWrapper<>();
        query.eq(UnionMemberApply::getMemberId, unionMemberApplyDTO.getMemberId());
        query.eq(UnionMemberApply::getUnionId, unionMemberApplyDTO.getUnionId());
        //query.eq(UnionMemberApply::getOptype,UnionMemberOptypeEnum.INVITE.name());
        query.eq(UnionMemberApply::getStatus,UnionMemberStatusEnum.WAIT_APPLY.name());
        query.last("limit 1");
        UnionMemberApply exist = this.getOne(query);
        if(null!=exist){
            if(exist.getUnionId().equals(unionMemberApplyDTO.getUnionId())){
                if (exist.getOptype().equals(UnionMemberOptypeEnum.APPLY.name())) {
                    throw new ServiceException("该用户已申请加入工会，请在申请审核中处理");
                }else {
                    throw new ServiceException(ResultCode.APPLY_SAME_UNION);
                }
            }else{
                throw new ServiceException(ResultCode.IN_OTHER_UNION);
            }
        }

        UnionLog unionLog = UnionLog.builder()
                .operationRemark("会长" + chariman.getUsername() + "邀请"+user.getUsername()+"加入工会:" + union.getUnionName())
                .createTime(new Date())
                .unionId(union.getId())
                .operationUserId(UserContext.getCurrentId())
                .operationUserName(Objects.requireNonNull(UserContext.getCurrentUser()).getUsername())
                .build();

        UnionMemberApply member = new UnionMemberApply(unionMemberApplyDTO);
        member.setStatus(UnionMemberStatusEnum.WAIT_APPLY.name());
        member.setOptype(UnionMemberOptypeEnum.INVITE.name());

        unionLogService.save(unionLog);
        this.save(member);
    }


    /**
     * 工会申请记录
     * @param unionId 工会ID
     * @param page
     * @return
     */
    @Override
    public Page<UnionMemberApply> getApplyByPage(String unionId, PageVO page,String status,String optype) {

        //查询加入申请和退出申请
        List<String> optypeList = new ArrayList<>();
        optypeList.add(UnionMemberOptypeEnum.APPLY.name());
        optypeList.add(UnionMemberOptypeEnum.QUIT.name());
        QueryWrapper<UnionMemberApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ap.union_id", unionId);
        if(StringUtils.isNotEmpty(status)){//查询条件：状态值不为空
            queryWrapper.eq("ap.status", status.toUpperCase());
        }
        if(StringUtils.isNotEmpty(optype)){//查询条件：类型值不为空
            queryWrapper.eq("ap.optype", optype.toUpperCase());
        }else{//查询条件：类型值为空,同时查申请加入工会和退出工会的数据
            queryWrapper.in("ap.optype",optypeList);
        }
        queryWrapper.orderByDesc("id");

        Page<UnionMemberApply> pageData =  unionMemberApplyMapper.getJoinRecordsByPage(PageUtil.initPage(page),queryWrapper);

        if (!pageData.getRecords().isEmpty()) {
            List<String> memberIdList = pageData.getRecords().stream().map(item -> item.getMemberId()).collect(Collectors.toList());
            List<User> userList = userService.findByIdList(memberIdList);

            pageData.getRecords().forEach(unionMember -> {
                User chairman = userList.stream().filter(item -> item.getId().equals(unionMember.getMemberId())).findFirst().orElse(null);
                if (null != chairman) {
                    unionMember.setMemberName(chairman.getNickName());
                    unionMember.setMemberHead(chairman.getFace());
                }
            });
        }

        return pageData;

    }

    /**
     * 邀请入会记录
     * @param unionId 工会ID
     * @param page
     * @return
     */
    @Override
    public Page<UnionMemberApply> getInviteByPage(String unionId, PageVO page) {
        QueryWrapper<UnionMemberApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ap.union_id", unionId);
        queryWrapper.eq("ap.optype", UnionMemberOptypeEnum.INVITE.name());
        queryWrapper.orderByDesc("id");

        Page<UnionMemberApply> pageData =  unionMemberApplyMapper.getJoinRecordsByPage(PageUtil.initPage(page),queryWrapper);


        if (!pageData.getRecords().isEmpty()) {
            List<String> memberIdList = pageData.getRecords().stream().map(item -> item.getMemberId()).collect(Collectors.toList());
            List<User> userList = userService.findByIdList(memberIdList);

            pageData.getRecords().forEach(unionMember -> {
                User chairman = userList.stream().filter(item -> item.getId().equals(unionMember.getMemberId())).findFirst().orElse(null);
                if (null != chairman) {
                    unionMember.setMemberName(chairman.getNickName());
                    unionMember.setMemberHead(chairman.getFace());
                }
            });
        }

        return pageData;
    }

    /**
     * 审核工会申请
     *
     * @param recordId 申请记录ID
     * @param status UnionMemberStatusEnum
     */
    @Override
    public void applyAuth(String recordId, String status) {
        if(StringUtil.isNullOrEmpty(recordId)){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }
        if(null == status){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }
        UnionMemberApply unionMemberApply = getById(recordId);
        if(null == unionMemberApply){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        Union union = unionMapper.selectById(unionMemberApply.getUnionId());
        if(null == union){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        log.info("工会会长ID：{}, 审批人ID：{}", union.getChairmanId(), UserContext.getCurrentId());
        if(!union.getChairmanId().equals(Objects.requireNonNull(UserContext.getCurrentUser()).getId())){
            //非会长邀请
            throw new ServiceException(ResultCode.INVALID_OPERATION);
        }

        User user = userService.getById(unionMemberApply.getMemberId());

        User chariman = userService.getById(union.getChairmanId());

        if(UnionMemberOptypeEnum.APPLY.name().equals(unionMemberApply.getOptype())){
            if(!UnionMemberStatusEnum.WAIT_APPLY.name().equals(unionMemberApply.getStatus())){
                //当前记录不是待审核状态
                throw new ServiceException(ResultCode.APPLY_STATUS_ERROR);
            }

            if(status.toUpperCase().equals(UnionMemberStatusEnum.PASS.name())){ //同意加入
                UnionMember member = new UnionMember();
                member.setUnionId(unionMemberApply.getUnionId());
                member.setJoinTime(new Date());
                member.setMemberId(unionMemberApply.getMemberId());
                member.setCity(unionMemberApply.getCity());
                member.setStatus(UnionMemberStatusEnum.PASS.name());
                unionMemberMapper.insert(member);

                //更改用户所属的工会
                if(null!=user){
                    user.setUnionId(unionMemberApply.getUnionId());
                    userService.updateById(user);
                }

                unionMemberApply.setJoinTime(new Date());

                if (StringUtils.isNotEmpty(user.getOpenId())) {
                    OpenAppUser openAppUser = userApi.getUserinfoByOpenId(user.getOpenId());
                    if (null != openAppUser) {
                        List<PojoGroupMember> groupMemberList = Lists.newArrayList();
                        PojoGroupMember groupMember = new PojoGroupMember();
                        groupMember.setMember_id(openAppUser.getUId());
                        groupMember.setType(ProtoConstants.GroupMemberType.GroupMemberType_Normal);
                        groupMemberList.add(groupMember);
                        addGroup(groupMemberList, union);
                    }
                }

            }else if(status.toUpperCase().equals(UnionMemberStatusEnum.REFUSE.name())){

            }else{
                throw new ServiceException(ResultCode.PARAMS_ERROR);
            }
            unionMemberApply.setStatus(status.toUpperCase());

            this.updateById(unionMemberApply);

            UnionLog unionLog = UnionLog.builder()
                    .operationRemark("会长" + chariman.getUsername() + "审核"+user.getUsername()+"入会申请，审核结果：" + status)
                    .createTime(new Date())
                    .unionId(union.getId())
                    .operationUserId(UserContext.getCurrentId())
                    .operationUserName(Objects.requireNonNull(UserContext.getCurrentUser()).getUsername())
                    .build();
            unionLogService.save(unionLog);

            applicationEventPublisher.publishEvent(
                    TransactionCommitSendMQEvent.builder()
                            .source("UNION_LOG")
                            .exchange(amqpExchangeProperties.getUnion())
                            .routingKey(UnionRoutingKey.ADD_UNION_LOG)
                            .message(unionLog)
                            .build());

        }else{
            throw new ServiceException(ResultCode.INVALID_OPERATION);
        }


    }


    private void addGroup(List<PojoGroupMember> groupMemberList, Union union) {
        // 加入群组
        if (!groupMemberList.isEmpty()) {
            try {
                User user = userService.getById(union.getChairmanId());
                OpenAppUser openAppUser = userApi.getUserinfoByOpenId(user.getOpenId());
                GroupAdmin.addGroupMembers(openAppUser.getUId(), union.getGroupId(), groupMemberList, new ArrayList<Integer>() {{
                    add(0);
                }}, null);
            }catch (Exception e) {
                log.error("添加群组成员失败:{}"+e.getMessage());
            }
        }
    }

    /**
     * 邀请审核
     * @param recordId 邀请记录ID
     * @param status
     */
    @Override
    public void inviteAuth(String recordId, String status) {
        if(StringUtil.isNullOrEmpty(recordId)){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }
        if(null == status){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }
        UnionMemberApply unionMemberApply = getById(recordId);
        if(null == unionMemberApply){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        Union union = unionMapper.selectById(unionMemberApply.getUnionId());
        if(null == union){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        User user = userService.getById(unionMemberApply.getMemberId());
        if(null == user){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        User chariman = userService.getById(union.getChairmanId());
        if(null == chariman){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        String statusDesc = "";
        if(UnionMemberOptypeEnum.INVITE.name().equals(unionMemberApply.getOptype())){
            if(!UnionMemberStatusEnum.WAIT_APPLY.name().equals(unionMemberApply.getStatus())){
                //当前记录不是待审核状态
                throw new ServiceException(ResultCode.APPLY_STATUS_ERROR);
            }
            if(status.equals(UnionMemberStatusEnum.PASS.name())){
                statusDesc = "同意";
                UnionMember member = new UnionMember();
                member.setUnionId(unionMemberApply.getUnionId());
                member.setJoinTime(new Date());
                member.setStatus(UnionMemberStatusEnum.PASS.name());
                member.setMemberId(unionMemberApply.getMemberId());
                unionMemberMapper.insert(member);

                user.setUnionId(unionMemberApply.getUnionId());
                userService.updateById(user);

                try {
                    if (StringUtils.isNotEmpty(user.getOpenId())) {
                        OpenAppUser openAppUser = userApi.getUserinfoByOpenId(user.getOpenId());
                        if (null != openAppUser) {
                            List<PojoGroupMember> groupMemberList = new ArrayList<>();
                            PojoGroupMember groupMember = new PojoGroupMember();
                            groupMember.setMember_id(openAppUser.getUId());
                            groupMember.setType(ProtoConstants.GroupMemberType.GroupMemberType_Normal);
                            groupMemberList.add(groupMember);

                            User unionUser = userService.getById(union.getChairmanId());
                            OpenAppUser unionUserOpenAppUser = userApi.getUserinfoByOpenId(unionUser.getOpenId());
                            GroupAdmin.addGroupMembers(unionUserOpenAppUser.getUId(), union.getGroupId(), groupMemberList, new ArrayList<Integer>() {{
                                add(0);
                            }}, null);
                        }
                    }
                }catch (Exception e) {
                    log.error("异常：{}",e.getMessage());
                }

            }else if(status.equals(UnionMemberStatusEnum.REFUSE.name())){
                statusDesc = "拒绝";
            }
            unionMemberApply.setStatus(status);
            this.updateById(unionMemberApply);

            UnionLog unionLog = UnionLog.builder()
                    .operationRemark("用户" + user.getUsername() + statusDesc+"加入工会:"+union.getUnionName())
                    .createTime(new Date())
                    .unionId(union.getId())
                    .operationUserId(UserContext.getCurrentId())
                    .operationUserName(Objects.requireNonNull(UserContext.getCurrentUser()).getUsername())
                    .build();
            unionLogService.save(unionLog);

            applicationEventPublisher.publishEvent(
                    TransactionCommitSendMQEvent.builder()
                            .source("UNION_LOG")
                            .exchange(amqpExchangeProperties.getUnion())
                            .routingKey(UnionRoutingKey.ADD_UNION_LOG)
                            .message(unionLog)
                            .build());


        }else{
            throw new ServiceException(ResultCode.INVALID_OPERATION);
        }
    }

    /**
     * 申请
     * @param memberId
     * @param unionId
     */
    @Override
    @Transactional
    public void quitApply(String memberId,String unionId) {
        if(StringUtil.isNullOrEmpty(memberId) || StringUtil.isNullOrEmpty(unionId)){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        LambdaQueryWrapper<UnionMemberApply> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UnionMemberApply::getMemberId,memberId);
        queryWrapper.eq(UnionMemberApply::getUnionId,unionId);
        queryWrapper.eq(UnionMemberApply::getOptype,UnionMemberOptypeEnum.QUIT);
        queryWrapper.last("limit 1");
        UnionMemberApply unionMemberApply = unionMemberApplyMapper.selectOne(queryWrapper);

        Union union = unionMapper.selectById(unionId);
        if(null == union){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        User user = userService.getById(memberId);
        if(null == user){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        String logRemark = "";

        if(null==unionMemberApply){
            unionMemberApply = new UnionMemberApply();
            unionMemberApply.setStatus(UnionMemberStatusEnum.WAIT_APPLY.name());
            unionMemberApply.setMemberId(memberId);
            unionMemberApply.setUnionId(unionId);
            unionMemberApply.setQuitTimes(1);
            unionMemberApply.setOptype(UnionMemberOptypeEnum.QUIT.name());
            unionMemberApplyMapper.insert(unionMemberApply);

            logRemark = "用户" + user.getUsername() + "申请退出工会:"+union.getUnionName();

        }else{
            Integer quitTimes = unionMemberApply.getQuitTimes();
            if(null != quitTimes && quitTimes >= 2){
                //申请退出超过两次，直接退群
                //工会成员 - 逻辑删除，user表的union_id设置为空
                LambdaUpdateWrapper<UnionMember> updateWrapper = new LambdaUpdateWrapper<UnionMember>();
                updateWrapper.eq(UnionMember::getMemberId,memberId);
                updateWrapper.set(UnionMember::getDeleteFlag,true);

                unionMemberMapper.update(null,updateWrapper);
                userService.clearUnion(memberId);

                unionMemberApply.setStatus(UnionMemberStatusEnum.PASS.name());
                unionMemberApply.setQuitTimes(++quitTimes);
                unionMemberApplyMapper.updateById(unionMemberApply);

                logRemark = "用户" + user.getUsername() + "直接退出工会:"+union.getUnionName();

            }else{
                unionMemberApply.setStatus(UnionMemberStatusEnum.WAIT_APPLY.name());
                unionMemberApply.setQuitTimes(++quitTimes);
                unionMemberApplyMapper.updateById(unionMemberApply);
                logRemark = "用户" + user.getUsername() + "申请退出工会:"+union.getUnionName();

            }
        }

        UnionLog unionLog = UnionLog.builder()
                .operationRemark(logRemark)
                .createTime(new Date())
                .unionId(union.getId())
                .operationUserId(UserContext.getCurrentId())
                .operationUserName(Objects.requireNonNull(UserContext.getCurrentUser()).getUsername())
                .build();
        unionLogService.save(unionLog);

        applicationEventPublisher.publishEvent(
                TransactionCommitSendMQEvent.builder()
                        .source("UNION_LOG")
                        .exchange(amqpExchangeProperties.getUnion())
                        .routingKey(UnionRoutingKey.ADD_UNION_LOG)
                        .message(unionLog)
                        .build());
    }

    /**
     * 我的申请
     * @param memberId
     * @param page
     * @return
     */
    @Override
    public Page<UnionMemberApply> getMyApplyByPage(String memberId, PageVO page){
        QueryWrapper<UnionMemberApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ap.member_id", memberId);
        queryWrapper.eq("ap.optype", UnionMemberOptypeEnum.APPLY.name());

        Page<UnionMemberApply> pageData =  unionMemberApplyMapper.getByPage(PageUtil.initPage(page),queryWrapper);

        if (!pageData.getRecords().isEmpty()) {
            pageData.getRecords().forEach(unionMemberApply -> {
                Union union = unionMapper.getUnionInfo(unionMemberApply.getUnionId());
                unionMemberApply.setUnionName(union.getUnionName());
                unionMemberApply.setChairmanName(union.getChairmanName());
                unionMemberApply.setChairmanPortrait(union.getChairmanPortrait());
                unionMemberApply.setMemberCount(Math.toIntExact(union.getMemberCount()));
            });
        }

        return pageData;

    }

    /**
     * 邀请我的
     * @param memberId
     * @param page
     * @return
     */
    @Override
    public Page<UnionMemberApply> getInviteMeByPage(String memberId, PageVO page){
        QueryWrapper<UnionMemberApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ap.member_id", memberId);
        queryWrapper.eq("ap.optype", UnionMemberOptypeEnum.INVITE.name());
        queryWrapper.orderByDesc("ap.create_time");
        Page<UnionMemberApply> pageData =  unionMemberApplyMapper.getByPage(PageUtil.initPage(page),queryWrapper);

        if (!pageData.getRecords().isEmpty()) {
            pageData.getRecords().forEach(unionMemberApply -> {
                Union union = unionMapper.getUnionInfo(unionMemberApply.getUnionId());
                unionMemberApply.setUnionName(union.getUnionName());
                unionMemberApply.setChairmanName(union.getChairmanName());
                unionMemberApply.setChairmanPortrait(union.getChairmanPortrait());
                unionMemberApply.setMemberCount(Math.toIntExact(union.getMemberCount()));
            });
        }
        return pageData;
    }


    /**
     * 退出工会审核
     * @param recordId 邀请记录ID
     * @param status
     */
    @Override
    public void quitAuth(String recordId, String status) {
        if(StringUtil.isNullOrEmpty(recordId)){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }
        if(null == status){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }
        UnionMemberApply unionMemberApply = getById(recordId);
        if(null == unionMemberApply){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        Union union = unionMapper.selectById(unionMemberApply.getUnionId());
        if(null == union){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        if(!union.getChairmanId().equals(Objects.requireNonNull(UserContext.getCurrentUser()).getId())){
            //非会长操作
            throw new ServiceException(ResultCode.INVALID_OPERATION);
        }

        User user = userService.getById(unionMemberApply.getMemberId());
        if(null == user){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        User chariman = userService.getById(union.getChairmanId());
        if(null == chariman){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        String statusDesc = "";
        if(UnionMemberOptypeEnum.QUIT.name().equals(unionMemberApply.getOptype())){
            if(!UnionMemberStatusEnum.WAIT_APPLY.name().equals(unionMemberApply.getStatus())){
                //当前记录不是待审核状态
                throw new ServiceException(ResultCode.APPLY_STATUS_ERROR);
            }
            if(status.equals(UnionMemberStatusEnum.PASS.name())){
                statusDesc = "同意";

                LambdaUpdateWrapper<UnionMember> updateWrapper = new LambdaUpdateWrapper<UnionMember>();
                updateWrapper.eq(UnionMember::getMemberId,unionMemberApply.getMemberId());
                updateWrapper.set(UnionMember::getDeleteFlag,true);
                unionMemberMapper.update(null,updateWrapper);

                userService.clearUnion(unionMemberApply.getMemberId());

                try {
                    // 退出群组
                    if (StringUtils.isNotEmpty(user.getOpenId())) {
                        OpenAppUser openAppUser = userApi.getUserinfoByOpenId(user.getOpenId());
                        if (null != openAppUser) {
                            GroupAdmin.quitGroup(openAppUser.getUId(), union.getGroupId(), new ArrayList<Integer>() {{
                                add(0);
                            }}, null);
                        }
                    }
                }catch (Exception e) {
                    log.error("退群异常：{}", e.getMessage());
                }

            }else if(status.equals(UnionMemberStatusEnum.REFUSE.name())){
                statusDesc = "拒绝";
            }
            unionMemberApply.setStatus(status);
            this.updateById(unionMemberApply);

            UnionLog unionLog = UnionLog.builder()
                    .operationRemark("会长" + chariman.getUsername() + statusDesc+user.getUsername()+"退出工会:"+union.getUnionName())
                    .createTime(new Date())
                    .unionId(union.getId())
                    .operationUserId(UserContext.getCurrentId())
                    .operationUserName(Objects.requireNonNull(UserContext.getCurrentUser()).getUsername())
                    .build();
            unionLogService.save(unionLog);

            applicationEventPublisher.publishEvent(
                    TransactionCommitSendMQEvent.builder()
                            .source("UNION_LOG")
                            .exchange(amqpExchangeProperties.getUnion())
                            .routingKey(UnionRoutingKey.ADD_UNION_LOG)
                            .message(unionLog)
                            .build());

        }else{
            throw new ServiceException(ResultCode.INVALID_OPERATION);
        }
    }



    @Override
    public UnionMemberApply myQuitStatus(){
        UnionMember unionMember = unionMemberMapper.getOneById(Objects.requireNonNull(UserContext.getCurrentUser()).getId());
        if(null == unionMember){
            throw new ServiceException(ResultCode.INVALID_OPERATION);
        }

        List<String> statusList = new ArrayList<>();
        statusList.add(UnionMemberStatusEnum.WAIT_APPLY.name());
        statusList.add(UnionMemberStatusEnum.REFUSE.name());
        statusList.add(UnionMemberStatusEnum.PASS.name());
        LambdaQueryWrapper<UnionMemberApply> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UnionMemberApply::getUnionId,unionMember.getUnionId());
        queryWrapper.eq(UnionMemberApply::getMemberId,unionMember.getMemberId());
        queryWrapper.eq(UnionMemberApply::getOptype,UnionMemberOptypeEnum.QUIT.name());
        queryWrapper.in(UnionMemberApply::getStatus,statusList);
        queryWrapper.last("limit 1");
        queryWrapper.orderByDesc(UnionMemberApply::getCreateTime);
        UnionMemberApply unionMemberApply = unionMemberApplyMapper.selectOne(queryWrapper);
        return unionMemberApply;

    }



    @Override
    public List<User> getListByName(String keyword){
        List<User> dataList = new ArrayList<>();
        List<Distribution> distributionList = distributionClient.getListByName(keyword);
        if(null!=distributionList && !distributionList.isEmpty()){
            List<String> userIdList = distributionList.stream().map(item->item.getMemberId()).collect(Collectors.toList());
            List<User> userList = userService.findByIdList(userIdList);
            if(null!=userList){
                userList.forEach(item->{
                    User one = new User();
                    one.setId(item.getId());
                    one.setUsername(item.getUsername());
                    one.setNickName(item.getNickName());
                    one.setFace(item.getFace());
                    dataList.add(one);
                });
            }
        }
        return dataList;
    }



}
